<?php

declare(strict_types=1);

namespace App\Activity\Listener;

use App\Activity\Event\Group;
use App\Common\Service\Generator;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Redis\RedisFactory;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * @Listener
 */
class GroupListener implements ListenerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    public function __construct(ContainerInterface $container,LoggerFactory $loggerFactory)
    {
        $this->container = $container;
        $this->logger = $loggerFactory->get('自动成团', 'autoGroup');
    }

    public function listen(): array
    {
        return [
            Group::class
        ];
    }

    public function process(object $event)
    {
        $acId = $event->acId;
        $needPeople = $event->needPeople;

        try {
            $iteratorIng = null;
            $iterator = null;
            $ing = "group{$acId}:ing";
            $success = "group{$acId}:success";
            $dels = [];
            $redis = $this->container->get(RedisFactory::class)->get('group');
            while ( $list = $redis->sScan($ing, $iteratorIng) ){
                if (!empty($list)) {
                    $generator = $this->container->get(Generator::class);
                    $name = $generator->nicknameDict();
                    $avatar = $generator->randAvatarOss();
                    $nameCount = count($name);
                    $avatarCount = count($avatar);
                    // 自动成团
                    $sAdd = [$success];
                    foreach ($list as $v) {
                        $memb = $redis->zCard($v);
                        $num = $needPeople - $memb;
                        $zAdd = [$v];
                        for ($i = 0; $i < $num; $i++) {
                            $rob = [
                                'mid' => 'b' . mt_rand(),
                                'orderNo' => mt_rand(),
                                'activityId' => $acId,
                                'nickname' => $name[mt_rand(0, $nameCount)],
                                'avatar' => $avatar[mt_rand(0, $avatarCount)],
                                'time' => time() + $i
                            ];
                            $zAdd = array_merge($zAdd, [time(), json_encode($rob)]);
                        }
                        $sAdd = array_merge($sAdd, [$v]);
                        call_user_func_array([$redis, 'zAdd'], $zAdd);
                    }
                    call_user_func_array([$redis, 'sAdd'], $sAdd);
                    // 自动成团后删除待分享/拼团中/团购活动
                    while(false !== ($del = $redis->scan($iterator,"share-*-{$acId}"))) {
                        foreach($del as $v) {
                            array_push($dels, $v);
                        }
                    }
                    array_push($dels, $ing);
                    $redis->del($dels);
                    unset($dels);
                    $this->logger->info("拼团{$acId}活动自动成团完毕", ['groupNumList' => $list]);
                }
            }// 未成团
        }catch (\Exception $e){
            $param = ['groupNumList' => $list, 'error' => $e->getMessage()];
            $this->logger->error("拼团{$acId}活动自动成团异常", $param);
        }

    }
}
